package com.javadroid.sgbd;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.javadroid.model.Data;
import com.javadroid.model.Data.Mysql;
 
public class ConnectionDataBase {
 
 
    public static Connection getConnection() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection con = null;
           	String[] prop = getProperties();
           	con = DriverManager.getConnection(prop[2], prop[0], prop[1]);
            return con;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return null;
    }
    
	private static String[] getProperties() {
		
		boolean servidorAppFog = false;
		
		if(servidorAppFog){
			String jsonProp = java.lang.System.getenv("VCAP_SERVICES");
			GsonBuilder buildJson = new GsonBuilder();
			Gson json = buildJson.create();
			
			jsonProp = jsonProp.replace("mysql-5.1", "mysql");
			Data obj = json.fromJson(jsonProp, Data.class);
			
			Mysql mysql = obj.getMysql().get(0);
			String[] properties = {mysql.getCredentials().getUsername(),mysql.getCredentials().getPassword(),"jdbc:mysql://"+mysql.getCredentials().getHost()+":"+mysql.getCredentials().getPort()+"/"+mysql.getCredentials().getName()};
			return properties;
		}else{
			String[] properties = {"root","mysql","jdbc:mysql://localhost:3306/smartnovelas"};
			return properties;
		}
	}
}